package com.example.common.network;

import com.example.common.utils.LogUtil;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class TokenRefreshInterceptor implements Interceptor {
    
    private static final String TAG = "TokenRefreshInterceptor";
    private TokenRefreshCallback refreshCallback;
    
    public interface TokenRefreshCallback {
        /**
         * 刷新Token
         * @return 刷新成功返回true，失败返回false
         */
        boolean refreshToken();
    }
    
    public TokenRefreshInterceptor(TokenRefreshCallback refreshCallback) {
        this.refreshCallback = refreshCallback;
    }
    
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Response response = chain.proceed(originalRequest);
        
        // 如果返回401未授权，尝试刷新Token
        if (response.code() == 401 && refreshCallback != null) {
            LogUtil.d(TAG, "Received 401, attempting to refresh token");
            
            synchronized (this) {
                // 关闭原始响应
                response.close();
                
                // 尝试刷新Token
                if (refreshCallback.refreshToken()) {
                    LogUtil.d(TAG, "Token refreshed successfully, retrying request");
                    
                    // 重新构建请求（会包含新的Token）
                    Request newRequest = originalRequest.newBuilder().build();
                    
                    // 重新发送请求
                    return chain.proceed(newRequest);
                } else {
                    LogUtil.e(TAG, "Token refresh failed");
                }
            }
        }
        
        return response;
    }
}